package com.chu.utils;

import com.chu.entity.Employee;
import com.chu.entity.Menu;
import com.chu.entity.Role;
import com.chu.mapper.MenuMapper;
import com.chu.mapper.RoleMapper;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

public class MyForm extends FormAuthenticationFilter {

    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private MenuMapper menuMapper;

    //认证成功的时候被调用
    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject,
                                     ServletRequest request, ServletResponse response) throws Exception {

        System.out.println("onLoginSuccess开始");

        //1.先得到用户的信息(用户名和密码)
        Employee employee = (Employee) subject.getPrincipal();
        Role role = roleMapper.selectByPrimaryKey(employee.getRoleid());
        //根据角色查询菜单
        List<Menu> menus = menuMapper.findMenusByRoleId(role.getRoleid());
        ArrayList firstList = new ArrayList();//对菜单列表分级 创建集合保存一级菜单
        for (Menu menu : menus) {
            if(menu.getUpmenuid()==0){//一级菜单
                ArrayList secondList = new ArrayList();//创建集合保存二级菜单
                for (Menu secondMenu : menus) {
                    if(menu.getMenuid()==secondMenu.getUpmenuid()){//如果菜单的父id等于一级菜单的id 二级菜单
                        //保存二级菜单
                        secondList.add(secondMenu);
                    }
                }
                //将二级菜单保存到一级菜单当中
                menu.setMenuList(secondList);
                //将一级菜单添加到集合当中
                firstList.add(menu);
            }
        }
        //将权限集合交给角色
        role.setMenuList(firstList);
        //保存角色对应的请求
        List<Menu> permissionList = menuMapper.findPermissionByRoleId(role.getRoleid());
        role.setPermissionList(permissionList);
        employee.setRole(role);

        HttpServletRequest request1 = (HttpServletRequest) request;
        request1.getSession().setAttribute("employee",employee);
        HttpServletResponse response1 = (HttpServletResponse) response;

        System.out.println("onLoginSuccess结束");

        response1.sendRedirect("/index.jsp");

        return false;
    }
}
